<template>
  <div style="padding: 20px;">
    <!-- 返回导航 -->
    <el-page-header @back="$router.go(-1)" content="我要报修"></el-page-header>
    
    <!-- 报修表单 -->
    <el-form 
      :model="form" 
      :rules="rules" 
      ref="formRef" 
      label-position="top"
      label-width="80px" 
      style="margin-top: 30px; max-width: 800px;"
    >
      <!-- 工程设备级联选择 -->
      <el-form-item label="工程设备" prop="selectedIds">
        <el-cascader 
          v-model="selectedIds"
          :options="empData"
          :props="{ 
            value: 'id', 
            label: 'name', 
            expandTrigger: 'hover',
            checkStrictly: true 
          }"
          @change="handleChange"
          style="width: 100%"
        />
      </el-form-item>

      <!-- 故障类型 -->
      <el-form-item label="故障类型" prop="fault_type">
        <el-select
          v-model="form.fault_type"
          placeholder="请选择故障类型"
          style="width: 100%"
        >
          <el-option label="传感器异常" value="sensor" />
          <el-option label="数据中断" value="data" />
          <el-option label="设备离线" value="offline" />
          <el-option label="其他问题" value="other" />
        </el-select>
      </el-form-item>

      <!-- 故障描述 -->
      <el-form-item label="详细情况" prop="bill_why">
        <el-input
          type="textarea"
          :rows="4"
          v-model="form.bill_why"
          placeholder="请详细描述故障现象"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <!-- 图片上传 -->
      <el-form-item label="现场照片">
        <el-upload
          action="http://116.62.41.227:7001/api/upload"
          list-type="picture-card"
          :on-success="handleUploadSuccess"
          :before-upload="beforeUpload"
          :limit="3"
          :file-list="fileList"
        >
          <i class="el-icon-plus"></i>
          <div slot="tip" class="el-upload__tip">
            最多上传3张图片，单张图片不超过5MB
          </div>
        </el-upload>
      </el-form-item>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button 
          type="primary" 
          @click="submitForm"
          :loading="submitting"
        >
          提交报修
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { get, post } from '@/utils/request'

export default {
  data() {
    return {
      submitting: false,
      selectedIds: [],
      empData: [],
      fileList: [],
      form: {
        engineer_id: null,
        device_id: null,
        bill_why: '',
        fault_type: '',
        attachments: []
      },
      rules: {
        selectedIds: [
          { required: true, message: '请选择工程和设备', trigger: 'change' }
        ],
        fault_type: [
          { required: true, message: '请选择故障类型', trigger: 'change' }
        ],
        bill_why: [
          { required: true, message: '请输入故障描述', trigger: 'blur' },
          { min: 10, message: '至少输入10个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 图片上传处理
    handleUploadSuccess(response, file) {
      this.form.attachments.push({
        url: response.data.url,
        name: file.name
      })
    },
    
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt5M = file.size / 1024 / 1024 < 5
      
      if (!isImage) {
        this.$message.error('只能上传图片文件！')
        return false
      }
      if (!isLt5M) {
        this.$message.error('图片大小不能超过5MB！')
        return false
      }
      return isImage && isLt5M
    },

    // 级联选择处理
    handleChange(value) {
      if (value.length >= 2) {
        this.form.engineer_id = value[0]
        this.form.device_id = value[1]
      }
    },

    // 获取工程设备数据
    async getEmpData() {
      try {
        const res = await get('/dashboard/findEngineerDeviceTree')
        this.empData = res.data
      } catch (error) {
        console.error('获取工程数据失败:', error)
      }
    },

    // 提交表单
    async submitForm() {
      try {
        await this.$refs.formRef.validate()
        
        if (!this.form.engineer_id || !this.form.device_id) {
          this.$message.warning('请选择工程和设备')
          return
        }

        this.submitting = true
        const payload = {
          ...this.form,
          reporter_id: this.$store.state.user.id,
          reporter_name: this.$store.state.user.realname
        }

        const res = await post('/workorder/repairOrder', payload)
        
        this.$notify({
          title: '提交成功',
          message: `工单号：${res.data.ticket_number}`,
          type: 'success',
          duration: 5000
        })
        
        this.$router.push({
          path: '/am/order/list',
          query: { forceRefresh: Date.now() }
        })
        
      } catch (error) {
        console.error('提交失败:', error)
        if (error.response) {
          this.$message.error(`提交失败：${error.response.data.message}`)
        } else {
          this.$message.error('网络连接异常，请稍后重试')
        }
      } finally {
        this.submitting = false
      }
    }
  },
  created() {
    this.getEmpData()
  }
}
</script>

<style scoped>
.el-page-header {
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.el-upload-list--picture-card .el-upload-list__item {
  margin: 0 8px 8px 0;
}

.el-upload__tip {
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
}
</style>